import 'package:elephant_fish/http/core/hi_error.dart';
import 'package:elephant_fish/http/core/hi_net.dart';
import 'package:elephant_fish/http/request/anchor_recommend_request.dart';
import 'package:elephant_fish/http/request/base_request.dart';
import 'package:elephant_fish/model/anchor.dart';
import 'package:elephant_fish/model/anchor_entity.dart';
import 'package:elephant_fish/util/TxUtils.dart';
import 'package:elephant_fish/util/size_util.dart';
import 'package:elephant_fish/widget/search_appbar.dart';
import 'package:elephant_fish/widget/search_list_card.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';

import 'login_page.dart';

class IndexSearchPage extends StatefulWidget {
  const IndexSearchPage({Key key}) : super(key: key);

  @override
  _IndexSearchPageState createState() => _IndexSearchPageState();
}

class _IndexSearchPageState extends State<IndexSearchPage> {
  List<AnchorEntity> anchorList = [];
  TextEditingController searchController = TextEditingController();
  bool _loading = false;
  ScrollController _scrollController = ScrollController();
  int pageIndex = 1;
  @override
  void initState() {
    super.initState();
    _scrollController.addListener(() {
      var dis = _scrollController.position.maxScrollExtent -
          _scrollController.position.pixels;
      //当距离底部不足300时加载更多
      if (dis < 300 && !_loading) {
        _loadData(loadMore: true);
      }
    });
    _loadData();
  }


  @override
  void dispose() {
    super.dispose();
    _scrollController.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        centerTitle: true,
        backgroundColor: Color(0xff140c3d),
        title: Row(
          children: <Widget>[
            //因为它是左右占比结构,所以使用Expanded 的flex
            Expanded(
              flex: 1,
              child: InkWell(
                //利用InkWell组件包裹其他组件,则拥有了点击事件
                  child: Container(
                    //所有组件垂直居中
                    alignment: Alignment.center,
                    height: SizeUtil.px(56),
                    padding: EdgeInsets.fromLTRB(0, 0, SizeUtil.px(30), 0),
                    //带有弧度的边框,有背景色
                    decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(53),
                      color: Color(0xff2b244d),
                    ),
                    child: Stack(
                      alignment: Alignment.center,
                      children: <Widget>[
                        Row(
                          //常用于Row和Column控件
                          mainAxisAlignment: MainAxisAlignment.start,
                          children: <Widget>[
                            SizedBox(width: SizeUtil.px(20)),
                            Icon(Icons.search, color: Color(0xff59527a)),
                            SizedBox(width: SizeUtil.px(20)), //常用于两个组件之间的分隔
                            Expanded(
                                child:TextField(
                                  controller: searchController,
                                  decoration: InputDecoration(
                                    isCollapsed: true,
                                    contentPadding: EdgeInsets.all(0),
                                    border: InputBorder.none,
                                    hintText: '@Make',
                                    hintStyle: TextStyle(color: Color(0xff59527a)),
                                  ),
                                  style: TextStyle(color: Color(0xff59527a)),
                                ) )
                          ],
                        ),
                      ],
                    ),
                  )),
            ),
            SizedBox(width: SizeUtil.px(14)),
            Expanded(
                flex: 0,
                child: InkWell(
                  child: Text(
                    '搜索',style: TextStyle(fontSize: SizeUtil.px(32),color: Color(0xffffffff)),
                  ),
                  onTap: (){
                    searchAnchor();
                  },
                )
            ),
          ],
        ),
        leading: GestureDetector(
          child: Icon(Icons.arrow_back_ios,size: SizeUtil.px(32),color: Color(0xfff3f3f3),),
          onTap: (){
            Navigator.pop(context);
          },
        ),
      ),
      backgroundColor: Color(0xff140c3d),
      body: Column(
        children: [

          Padding(padding: EdgeInsets.only(left:  SizeUtil.px(16),top:  SizeUtil.px(43)),
            child:  Row(
              children: [
                Padding(padding: EdgeInsets.only(left: SizeUtil.px(9)),
                  child: Container(
                    width: SizeUtil.px(4),
                    height: SizeUtil.px(43),
                    decoration: BoxDecoration(
                      color: Color(0xffff215d),
                      shape: BoxShape.rectangle,
                      borderRadius: BorderRadius.all(Radius.circular(2)),
                    ),
                  )
                ),
                Padding(padding: EdgeInsets.only(left: SizeUtil.px(9)),
                  child: Text('推荐主播',
                    style: TextStyle(
                      fontSize: SizeUtil.px(28),color: Color(0xfff3f3f3),
                    ),
                  ),
                ),

              ],
            ),
          ),
          Expanded(child:
            ListView.builder(
                itemCount: anchorList.length,
                controller: _scrollController,
                shrinkWrap: true,
                itemBuilder:(context,index){
                  return SearchListCard(anchor: anchorList[index],);
                }
            ),
          ),
        ],
      ),
    );
  }

  _loadData({loadMore = false})async{
    _loading = true;
    if (!loadMore) {
      pageIndex = 1;
    }
    var currentIndex = pageIndex + (loadMore ? 1 : 0);
    print('loading:currentIndex:$currentIndex');
    try {
      SharedPreferences prefs = await SharedPreferences.getInstance();
      String appToken = prefs.getString('app-token');
      BaseRequest request = AnchorRecommendRequest();
      request
          .add('page', currentIndex)
          .add('type', 2)
          .addHeader('usertoken', appToken);
      var result = await HiNet.getInstance().fire(request);
      if (result['code'] == -1) {
        TxUtils.showErrorToast('登录失效，请重新登录', context);
        Navigator.pop(context);
        Navigator.of(context).push(MaterialPageRoute(
          builder: (context) {
            return LoginPage(
              arguments: {'loginCode': '-1'},
            );
          },
        ));
      } else if (result['code'] == 0) {
        List<Map<String, dynamic>> listMap =
        new List<Map<String, dynamic>>.from(result['data']);
        List<AnchorEntity> list = List();
        for (int i = 0; i < listMap.length; i++) {
          list.add(AnchorEntity.fromJson(listMap[i]));
        }
        setState(() {
          if (loadMore) {
            if (list.isNotEmpty) {
              //合成一个新数组
              anchorList = [...anchorList, ...list];
              pageIndex++;
            }
          } else {
            anchorList = list;
          }
        });
        Future.delayed(Duration(milliseconds: 1000), () {
          _loading = false;
        });
      }
    } on NeedAuth catch (e) {
      print(e);
    } on HiNetError catch (e) {
      print(e);
    }
  }

  Future<void> searchAnchor() async {
    String search = searchController.text;
    SharedPreferences prefs = await SharedPreferences.getInstance();
    String appToken = prefs.getString('app-token');
    BaseRequest request = AnchorRecommendRequest();
    request
        .add('name', search)
        .addHeader('usertoken', appToken);
    var result = await HiNet.getInstance().fire(request);
    if (result['code'] == -1) {
      TxUtils.showErrorToast('登录失效，请重新登录', context);
      Navigator.pop(context);
      Navigator.of(context).push(MaterialPageRoute(
        builder: (context) {
          return LoginPage(
            arguments: {'loginCode': '-1'},
          );
        },
      ));
    } else if (result['code'] == 0) {
      List<Map<String, dynamic>> listMap =
      new List<Map<String, dynamic>>.from(result['data']);
      List<AnchorEntity> list = List();
      for (int i = 0; i < listMap.length; i++) {
        list.add(AnchorEntity.fromJson(listMap[i]));
      }
      setState(() {
        anchorList = list;
      });

    }
  }
}
